﻿using UnityEngine;
using System.Collections;
using System.Net.Sockets;
using System;

public static class Extensions {
	
	public static byte[] GetBytes(this string str)
	{
		byte[] bytes = new byte[str.Length * sizeof(char)];
		System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
		return bytes;
	}
	
	public static string GetString(this byte[] bytes)
	{
		char[] chars = new char[bytes.Length / sizeof(char)];
		System.Buffer.BlockCopy(bytes, 0, chars, 0, bytes.Length);
		return new string(chars);
	}

	public static short ReadShort(this Socket socket) {
		var bytes = new byte[2];
		socket.Receive(bytes, 2, SocketFlags.None);
		return BitConverter.ToInt16(bytes, 0);
	}
	
	public static int ReadInt(this Socket socket) {
		var bytes = new byte[4];
		socket.Receive(bytes, 4, SocketFlags.None);
		return BitConverter.ToInt32(bytes, 0);
	}
	
	public static float ReadFloat(this Socket socket) {
		var bytes = new byte[4];
		socket.Receive(bytes, 4, SocketFlags.None);
		return BitConverter.ToSingle(bytes, 0);
	}
	
	public static byte[] SerializePosition(this Transform trans) {
		return ((Vector2)trans.position).SerializePosition();
	}

	public static byte[] SerializePosition(this Vector2 pos) {
		var bytes = new byte[RemotePlayer.PACKET_SIZE_POSITION];
		BitConverter.GetBytes(RemotePlayer.COMMAND_POSITION).CopyTo(bytes,0);
		BitConverter.GetBytes(pos.x).CopyTo(bytes,2);
		BitConverter.GetBytes(pos.y).CopyTo(bytes,6);
		return bytes;
	}
}
